package com.itheima.web.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = {"/pages/*","/store/*","/system/*"})
public class AuthenticationFilter implements Filter {


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //1 从session中获取用户信息
        Object user = request.getSession().getAttribute("user");
        //3 如果为null,说明还没有登录，重定向到登录页面
        if(user==null){
            //获取拦截到的路径，保存到session中，后期登录成功之后跳转到这个路径中
            String requestURI = request.getRequestURI();
            request.getSession().setAttribute("sendRedirect",requestURI);
            //拦截到了
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {}
    public void destroy() {}
}
